<?php 

namespace pmvc\mvc\controller;

class FormErrors {

	private $errors = Array();
	
	public function addGlobalError($message) {
		if (!array_key_exists("globalErrors", $this->errors)) {
			$this->errors["globalErrors"] = Array();
		}
		$this->errors["globalErrors"][] = $message;
	}
	
	public function addFieldError($field, $message) {
		if (!array_key_exists("fieldErrors", $this->errors)) {
			$this->errors["fieldErrors"] = Array();
		}
		if (!array_key_exists($field, $this->errors["fieldErrors"])) {
			$this->errors["fieldErrors"][$field] = Array();
		}
		$this->errors["fieldErrors"][$field][] = $message;
	}
	
	public function clearFieldErrors($field=FALSE) {
		if (!array_key_exists("fieldErrors", $this->errors)) {
			return;
		} else if ($field===FALSE) {
			$this->errors["fieldErrors"] = Array();
		} else {
			$this->errors["fieldErrors"][$field] = Array();
		}
	}
	
	public function clearGlobalErrors() {
		if (!array_key_exists("globalErrors", $this->errors)) {
			return;
		} else {
			$this->errors["globalErrors"] = Array();
		}
	}
	
	public function clearAllErrors() {
		$this->errors->exchangeArray(Array());
	}
	
	public function hasErrors() {
		if (array_key_exists("globalErrors", $this->errors)
			&& count($this->errors["globalErrors"])>0) {
			return true;
		} else if (array_key_exists("fieldErrors", $this->errors)) {
			foreach ($this->errors["fieldErrors"] as $fieldError) {
				if (count($fieldError)>0) {
					return true;
				}
			}
		}
		return false;
	}

	public function get() {
		return $this->errors;
	}
}

?>